package com.loiot.baqi.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;

public class HdHttpUtils {




	private  String cookies = "";
	
	
	/**
	 * 登陆主方法
	 * @param userName
	 * @param pwd
	 * @param yzm
	 * @throws FailingHttpStatusCodeException
	 * @throws IOException
	 * @throws InterruptedException 
	 */
	public  String login(String userName, String pwd, String yzm) throws Exception{
		//获取授权信息
		String authUrl = "http://wa.hunteron.com/api/ucenter/link?_t="+System.currentTimeMillis()+"&date="+System.currentTimeMillis()+"&loadingCover=false";
		String authorize = urlGet(authUrl,1000,2000);
		Map<String, Object> jsonMap = JsonToObject.parseJSON2Map(authorize);
		Map<String, Object> dataMap = (Map<String, Object>) jsonMap.get("data");
		String realm = (String) dataMap.get("realm");
		String nonce = (String) dataMap.get("nonce");
		String a = getMD5Str(pwd);
		String b = getMD5Str(a + "5OGP56W65A6D6LSD") + "x";
		String o = jsFunction(a, userName,realm, nonce);
		String s = jsFunction(b, userName,realm, nonce);
		
		//登陆
		String loginUrl = "http://hd.hunteron.com/api/ucenter/login?_t="+System.currentTimeMillis();
		Map<String, String > params = new HashMap<String, String>();
		params.put("loginName",userName);
		params.put("authorizeCode",o);
		params.put("twoAuthorizeCode",s);
		params.put("noRemind","true");
		params.put("imageVeriCode",yzm);
		String loginResult = httpPost(loginUrl, params);
		return loginResult;
	}

	/**
	 * httpGet请求
	 * @throws InterruptedException 
	 * 
	 */
	public  String httpGet(String url,int min,int max) throws Exception{
		String result;
			System.out.println("fetch url:"+url);
			Thread.sleep(com.loiot.commons.utils.RandomUtil.nextInt(min, max));

			CloseableHttpClient client = HttpClients.createDefault();
			HttpGet get = new HttpGet(url);
			get.addHeader("Host", "wa.hunteron.com");
			get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:46.0) Gecko/20100101 Firefox/46.0");
			get.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
			get.addHeader("Accept-Encoding", "gzip, deflate");
			get.addHeader("DNT","1");
			get.addHeader("t","web");
			get.addHeader("v","1.0");
			get.addHeader("X-TOKEN","");
			get.addHeader("tc",String.valueOf(System.currentTimeMillis()));
			get.addHeader("res","1440_900");
			get.addHeader("pd","wa");
			get.addHeader("pdt","web");
			get.addHeader("pdv","2.0.0");
			get.addHeader("uipos","null");
			get.addHeader("r","#/index?redirect=http%253A%252F%252Fwa.hunteron.com%252F%2523%252Fpositions%252Fmatch");
			get.addHeader("Referer","http://wa.hunteron.com/");
			get.addHeader("Cookie", cookies);
			CloseableHttpResponse resp = client.execute(get);
			getCookies(resp);
			HttpEntity entity = resp.getEntity();
			result = EntityUtils.toString(entity);
			return result;
	}
	
	/**
	 * post请求
	 * @throws IOException 
	 * @throws ParseException 
	 * 
	 */
	public  String httpPost(String url, Map<String, String> params) throws ParseException, IOException {
		String result = "";
			CloseableHttpClient client = HttpClients.createDefault();
			HttpPost post = new HttpPost(url);
			post.addHeader("Host", "wa.hunteron.com");
			post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:46.0) Gecko/20100101 Firefox/46.0");
			post.addHeader("Accept","application/json, text/plain, */*");
			post.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
			post.addHeader("Accept-Encoding", "gzip, deflate");
			post.addHeader("DNT","1");
			post.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
			post.addHeader("t","web");
			post.addHeader("v","1.0");
			post.addHeader("X-TOKEN","");
			post.addHeader("tc",String.valueOf(System.currentTimeMillis()));
			post.addHeader("res","1440_900");
			post.addHeader("pd","wa");
			post.addHeader("pdt","web");
			post.addHeader("pdv","2.0.0");
			post.addHeader("uipos","null");
			post.addHeader("r","http://wa.hunteron.com/#/positions/match#/index?redirect=http%253A%252F%252Fwa.hunteron.com%252F%2523%252Fpositions%252Fmatch");
			post.addHeader("Referer","http://wa.hunteron.com/");
			post.addHeader("Cookie", cookies);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			for (String key : params.keySet()) {
				nvps.add(new BasicNameValuePair(key, params.get(key)));
			}
			post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			 
			CloseableHttpResponse resp = client.execute(post);
			getCookies(resp);
			HttpEntity entity = resp.getEntity();
			result = EntityUtils.toString(entity);
		
		return result;
	}
	
	/**
	 * get请求
	 * @param url
	 * @return
	 * @throws InterruptedException 
	 */
	public  String urlGet(String url,int min,int max) throws Exception{
		String result;
			System.out.println("fetch url:"+url);
			//Thread.sleep(com.loiot.commons.utils.RandomUtil.nextInt(min, max));
			HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Host", "wa.hunteron.com");
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:46.0) Gecko/20100101 Firefox/46.0");
			conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
			conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
			conn.setRequestProperty("DNT","1");
			conn.setRequestProperty("t","web");
			conn.setRequestProperty("X-TOKEN:","");
			conn.setRequestProperty("v","1.0");
			conn.setRequestProperty("tc",String.valueOf(System.currentTimeMillis()));
			conn.setRequestProperty("res","1440_900");
			conn.setRequestProperty("pd","wa");
			conn.setRequestProperty("pdt","web");
			conn.setRequestProperty("pdv","2.0.0");
			conn.setRequestProperty("uipos","null");
			conn.setRequestProperty("r","#/index?redirect=http%253A%252F%252Fwa.hunteron.com%252F%2523%252Fpositions%252Fmatch");
			conn.setRequestProperty("Referer","http://wa.hunteron.com/");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.connect();
			Map<String, List<String>> headerFields = conn.getHeaderFields();
			List<String> cookieList = headerFields.get("Set-Cookie");
			for(String cookie : cookieList){
				cookies = cookies + cookie + ";";
			}
			System.out.println(headerFields);
			InputStream is = conn.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String line = null;
			StringBuffer sb  = new StringBuffer();
			while((line = br.readLine()) != null){
				sb.append(line);
			}
			result = sb.toString();
			return result;
		}
	
	/**
	 * 获取cookie
	 * @param response
	 */
	public  void getCookies(CloseableHttpResponse response){
		for (Header header : response.getHeaders("Set-Cookie")) {
			if (null != header) {
				cookies = header.getName() + "=" + header.getValue() + ";"; 
			}
		}
	}
	
	public  String jsFunction(String a0, String userName,  String realm, String nonce) {
		String a1 = getMD5Str(userName + ":" + realm + ":" + a0);
		String r = getMD5Str("POST:/ucenter/login");
		String o = getMD5Str(a1 + ":" + nonce + ":" + r);
		return o;
	}
	

	
	/**
	 * md5工具方法
	 * @param str
	 * @return
	 */
	public  String getMD5Str(String str) {  
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		    messageDigest.reset();  
			messageDigest.update(str.getBytes("UTF-8"));
		    byte[] byteArray = messageDigest.digest();  
	
		    StringBuffer md5StrBuff = new StringBuffer();  
	
		    for (int i = 0; i < byteArray.length; i++) {              
		        if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)  
		            md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));  
		        else  
		            md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));  
		    }  
		    
		    return md5StrBuff.toString();  
	    
		}catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	public String getCookies() {
		return cookies;
	}

	public void setCookies(String cookies) {
		this.cookies = cookies;
	}
}
